<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\controller\Base;
use app\common\model\GoodsList;
use app\common\model\RankWeek;
use app\common\model\RankMonth;
use app\common\model\User;
use app\common\model\ProfitPay;
use app\common\model\ProfitRank;
use app\common\model\Order;
use think\facade\Db;
use \think\Request;

class Rank extends Base
{

    /**
     * 周榜排行奖励
     */
    public function rank_week()
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        #当前日期
        $sdefaultDate = date("Y-m-d");
        #$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $first = 1;
        #获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $w = date('w', strtotime($sdefaultDate));
        #获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $week_start = date('Y-m-d', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));
        #本周结束日期
        $week_end = strtotime("$week_start +6 days");
        $week_start = strtotime($week_start);
        $week_end = $week_end + 86399;

        #我的排名
        $my_rank = '暂未上榜';
        $my_prize_title = 0;
        $my_prize_imgurl = 0;
        $my_order_total = Order::field('order_total')
            ->where('user_id', '=', $user_id)
            ->where('addtime', 'between', [$week_start, $week_end])
            ->where('status', '=', 1)
            ->where('order_type', '<', 5)
            ->sum('order_total');
        $my_order_total = $my_order_total ? $my_order_total : 0;
        #排行榜
        $data = Order::field('user_id,sum(`order_total`) as order_total')
            ->append(['user_info'])
            ->where('addtime', 'between', [$week_start, $week_end])
            ->where('status', '=', 1)
            ->where('order_type', '<', 5)
            ->group('user_id')
            ->order('order_total desc,user_id asc')
            ->limit(30)
            ->select()->toArray();
        foreach ($data as $key => &$value) {
            $rank = $key + 1;
            $value['rank'] = $rank;
            $value['order_total'] = $value['order_total'] * 1;
            $value['nickname'] = $value['user_info']['nickname'];
            $value['headimg'] = $value['user_info']['headimg'];
            #奖品信息
            $prize_info = GoodsList::field('title,imgurl')
                ->where('goods_id', '=', -1)
                ->where('rank', '=', $rank)
                ->find();
            if ($prize_info) {
                $value['prize_title'] = $prize_info['title'];
                $value['prize_imgurl'] = imageUrl($prize_info['imgurl']);
            } else {
                $value['prize_title'] = '';
                $value['prize_imgurl'] = '';
            }
            #判断会员是否在排名里面
            if ($value['user_id'] == $user_id) {
                $my_rank = $rank;
                $my_prize_title = $value['prize_title'];
                $my_prize_imgurl = $value['prize_imgurl'];
            }
            unset($value['user_info']);
        }
        $new_data = [
            'date' => (date('m月d日', $week_start) . '-' . date('m月d日', $week_end)),
            'end_date' => $week_end,
            'my_rank' => [
                'my_rank' => $my_rank,
                'my_prize_title' => $my_prize_title,
                'my_prize_imgurl' => $my_prize_imgurl,
                'my_order_total' => $my_order_total,
                'my_nickname' => $user['nickname'],
                'my_headimg' => imageUrl($user['headimg']),
            ],
            'data' => $data,
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    /**
     * 月榜排行奖励
     */
    public function rank_month()
    {
        $user = $this->getUser();
        $user_id = $user['id'];
        #获取本月开始的时间戳
        $beginThismonth = mktime(0, 0, 0, (int)date('m'), 1, (int)date('Y'));
        #获取本月结束的时间戳
        $endThismonth = mktime(23, 59, 59, (int)date('m'), (int)date('t'), (int)date('Y'));

        #我的排名
        $my_rank = '暂未上榜';
        $my_prize_title = 0;
        $my_prize_imgurl = 0;
        $my_order_total = Order::field('order_total')
            ->where('user_id', '=', $user_id)
            ->where('addtime', 'between', [$beginThismonth, $endThismonth])
            ->where('status', '=', 1)
            ->where('order_type', '<', 5)
            ->sum('order_total');
        $my_order_total = $my_order_total ? $my_order_total : 0;
        #排行榜
        $data = Order::field('user_id,sum(`order_total`) as order_total')
            ->append(['user_info'])
            ->where('addtime', 'between', [$beginThismonth, $endThismonth])
            ->where('status', '=', 1)
            ->where('order_type', '<', 5)
            ->group('user_id')
            ->order('order_total desc,user_id asc')
            ->limit(30)
            ->select()->toArray();
        foreach ($data as $key => &$value) {
            $rank = $key + 1;
            $value['rank'] = $rank;
            $value['order_total'] = $value['order_total'] * 1;
            $value['nickname'] = $value['user_info']['nickname'];
            $value['headimg'] = $value['user_info']['headimg'];
            #奖品信息
            $prize_info = GoodsList::field('title,imgurl')
                ->where('goods_id', '=', -2)
                ->where('rank', '=', $rank)
                ->find();
            if ($prize_info) {
                $value['prize_title'] = $prize_info['title'];
                $value['prize_imgurl'] = imageUrl($prize_info['imgurl']);
            } else {
                $value['prize_title'] = '';
                $value['prize_imgurl'] = '';
            }
            #判断会员是否在排名里面
            if ($value['user_id'] == $user_id) {
                $my_rank = $rank;
                $my_prize_title = $value['prize_title'];
                $my_prize_imgurl = $value['prize_imgurl'];
            }
            unset($value['user_info']);
        }
        $new_data = [
            'date' => (date('m月d日', $beginThismonth) . '-' . date('m月d日', $endThismonth)),
            'end_date' => $endThismonth,
            'my_rank' => [
                'my_rank' => $my_rank,
                'my_prize_title' => $my_prize_title,
                'my_prize_imgurl' => $my_prize_imgurl,
                'my_order_total' => $my_order_total,
                'my_nickname' => $user['nickname'],
                'my_headimg' => imageUrl($user['headimg']),
            ],
            'data' => $data,
        ];
        return $this->renderSuccess("请求成功", $new_data);

    }
    
    //排行榜
    public function ranks(Request $request)
    {
        $user = $this->getUser();
        $type = request()->param('type/d'); #1=日榜单 2=周榜单 3=月榜单
        $sdefaultDate = date("Y-m-d");
        if ($type == '1') {
            $time_start = strtotime($sdefaultDate);
            $time_end = $time_start + 86399;
        } else if ($type == '2') {
            #当前日期
            $sdefaultDate = date("Y-m-d");
            #$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
            $first = 1;
            #获取当前周的第几天 周日是 0 周一到周六是 1 - 6
            $w = date('w', strtotime($sdefaultDate));
            #获取本周开始日期，如果$w是0，则表示周日，减去 6 天
            $week_start = date('Y-m-d', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));
            #本周结束日期
            $week_end = strtotime("$week_start +6 days");
            $time_start = strtotime($week_start);
            $time_end = $week_end + 86399;
        } else if ($type == '3') {
            #获取本月开始的时间戳
            $time_start = mktime(0, 0, 0, (int)date('m'), 1, (int)date('Y'));
            #获取本月结束的时间戳
            $time_end = mktime(23, 59, 59, (int)date('m'), (int)date('t'), (int)date('Y'));
        } else {
            return $this->renderError("参数错误：type");
        }

        $where = [];
        $where[] = ['addtime', 'between', [$time_start, $time_end]];
        $data = ProfitRank::where($where)->group('user_id')->field('user_id, sum(`change_money`) as total_money')->order('total_money desc, user_id asc')->paginate(['list_rows' => 15, 'query' => request()->param()]);
        $top_three = $current_user = [];
        $current_user_id = 0;
        $current_rank = $current_key =  -10;
        foreach ($data as $k => $val) {
            $rank = $k + 1;
            $data[$k]['rank'] = $rank;
            $data[$k]['total_money_copy'] = $val['total_money'] * 1;
            $user_info = User::getInfo(['id'=> $val['user_id']], 'nickname,headimg,mobile');
            $data[$k]['nickname'] = $user_info['nickname'];
            $data[$k]['headimg'] = imageUrl($user_info['headimg']);
   
            $data[$k]['total_money'] = '******'; // 客户要求全部隐藏
            
            // if ($user['id'] == $data[$k]['user_id']) {
            //     $current_user[] = $data[$k];
            //     $current_user_id = $data[$k]['user_id'];
            //     $current_rank = $rank;
            // }
            
            // if ($current_user_id > 0) {
            //     if ( $current_rank + 1  == $rank || $current_rank  == $rank || $current_rank - 1  == $rank) {
            //         $data[$k]['total_money'] = $data[$k]['total_money_copy'] * 1;
            //     } else {
            //         $data[$k]['total_money'] = '******';
            //     }
            //     $current_key = $current_rank - 2;
                
            // }  else {
            //     $data[$k]['total_money_copy'] = $val['total_money'] * 1;
            //     $data[$k]['total_money'] = '******';
            // }
            
            if ($rank < 4) {
                $top_three[] = $data[$k];
            }
        }
        
        // if ($current_key >=0 ) {
        //     $data[$current_key]['total_money'] = $data[$current_key]['total_money_copy'];
        // }
        return $this->renderSuccess("请求成功", compact('data', 'top_three', 'current_user'));
    }

}
